package com.ytjj.qmyx.mall.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.ytjj.qmyx.mall.service.EsService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.search.SearchHits;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 *
 * @version 1.0
 *
 */
@Service
@Slf4j
public class EsServiceImpl implements EsService {

    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;

    @Override
    public <T> List<T> query(SearchQuery activityRecommendQuery,Class<T> clazz) {
        return elasticsearchTemplate.query(activityRecommendQuery, response -> {
            SearchHits hits = response.getHits();
            return Arrays.stream(hits.getHits())
                    .map(item -> {
                        log.debug(JSONObject.toJSONString(item.getSourceAsMap()));
                        return JSONObject.parseObject(JSONObject.toJSONString(item.getSourceAsMap()),clazz);
                    })
                    .collect(Collectors.toList());
        });
    }

    @Override
    public Long count(SearchQuery activityRecommendQuery) {
        return elasticsearchTemplate.count(activityRecommendQuery);
    }


}
